有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解析XML仅获取注释和日期值

嘿,我只是想看看我是否可以读取XML文件并只收集日期格式为YYYY-MM-DD的标记

Here is an online example: https://repl.it/repls/MedicalIgnorantEfficiency

下面是要分析的xml示例:

<?xml version="1.0" encoding="UTF-8"?>
<ncc:Message xmlns:ncc="http://blank/1.0.6" 
xmlns:cs="http://blank/1.0.0" 
xmlns:jx="http://blank/1.0.0"
xmlns:jm="http://blank/1.0.0"
xmlns:n-p="http://blank/1.0.0"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://blank/1.0.6/person person.xsd">
    <ncc:DataSection>
        <ncc:PersonResponse>
            <!-- Message -->
            <cs:CText cs:type="No">NO WANT</cs:CText>
            <jm:CaseID>
                <!-- OEA -->
                <jm:ID>ABC123</jm:ID>
            </jm:CaseID>
            <jx:PersonName>
                <!-- NAM -->
                <jx:GivenName>Arugula</jx:GivenName>
                <jx:MiddleName>Pibb</jx:MiddleName>
                <jx:SurName>Atari</jx:SurName>
            </jx:PersonName>
            <!-- DOB -->
            <ncc:PersonBirthDateText>1948-05-11</ncc:PersonBirthDateText>
            <jx:PersonDetails>
                <!-- SXC -->
                <jx:PersonSSN>
                    <jx:ID/>
                </jx:PersonSSN>
            </jx:PersonDetails>
            <n-p:Activity>
                <!--DOZ-->
                <jx:ActivityDate>1996-04-04</jx:ActivityDate>
                <jx:HomeAgency xsi:type="cs:Organization">
                    <!-- ART -->
                    <jx:Organization>
                        <jx:ID>ZR5981034</jx:ID>
                    </jx:Organization>
                </jx:HomeAgency>
            </n-p:Activity>
            <jx:PersonName>
                <!-- DOB Newest -->
                <ncc:BirthDateText>1993-05-12</ncc:BirthDateText>
                <ncc:BirthDateText>1993-05-13</ncc:BirthDateText>
                <ncc:BirthDateText>1993-05-14</ncc:BirthDateText>
                <jx:IDDetails xsi:type="cs:IDDetails">
                    <!-- SMC Checker -->
                    <jx:SSNID>
                        <jx:ID/>
                    </jx:SSNID>
                </jx:IDDetails>
            </jx:PersonName>
        </ncc:PersonResponse>
    </ncc:DataSection>
</ncc:Message>

我希望获得日期值注释,该注释位于这些日期值之上。对于上面的示例xml,类似以下内容:

Comment: < !-- DOB --> (ncc:DataSection/ncc:PersonResponse)

Date: 1948-05-11 (ncc:DataSection/ncc:PersonResponse/ncc:PersonBirthDateText)

Comment: < !-- DOZ --> (ncc:DataSection/ncc:PersonResponse/n-p:Activity)

Date: 1996-04-04 (ncc:DataSection/ncc:PersonResponse/n-p:Activity/jx:ActivityDate)

Comment: < !-- DOB Newest --> (ncc:DataSection/ncc:PersonResponse/jx:PersonName)

Date:

  1993-05-12 (ncc:DataSection/ncc:PersonResponse/jx:PersonName/ncc:BirthDateText)
  1993-05-13 (ncc:DataSection/ncc:PersonResponse/jx:PersonName/ncc:BirthDateText)
  1993-05-14 (ncc:DataSection/ncc:PersonResponse/jx:PersonName/ncc:BirthDateText)

我尝试使用的代码是:

public static void xpathNodes() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    File file = new File(base_);
    XPath xPath = XPathFactory.newInstance().newXPath();
    //String expression = "//*[not(*)]";
    String expression = "([0-9]{4})-([0-9]{2})-([0-9]{2})";
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse(file);
    document.getDocumentElement().normalize();
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); i++) {
        System.out.println(getXPath(nodeList.item(i)));
    }
}

private static String getXPath(Node node) {
    Node parent = node.getParentNode();

    if (parent == null) {
        return node.getNodeName();
    }

    return getXPath(parent) + "/" + node.getNodeName();
}

public static void main(String[] args) throws Exception {
    xpathNodes();
}

我知道正则表达式(([0-9]{4})-([0-9]{2})-([0-9]{2}))的工作原理与我在记事本+中使用的一样,它在那里可以很好地找到打开的xml文件中的日期

我当前收到错误信息:

Exception in thread "main" javax.xml.transform.TransformerException: A location path was expected, but the following token was encountered: [

这甚至还没有考虑到评论

任何帮助都会很好


共 (2) 个答案

  1. # 1 楼答案

    对于不带正则表达式的XPath 1.0表达式,您最好使用:

    //*[string-length()=10]
       [number(substring(.,1,4))=substring(.,1,4)]
       [substring(.,5,1)='-']
       [number(substring(.,6,2))=substring(.,6,2)]
       [substring(.,8,1)='-']
       [number(substring(.,9,2))=substring(.,9,2)]
    |
    //*[string-length()=10]
       [number(substring(.,1,4))=substring(.,1,4)]
       [substring(.,5,1)='-']
       [number(substring(.,6,2))=substring(.,6,2)]
       [substring(.,8,1)='-']
       [number(substring(.,9,2))=substring(.,9,2)]
       /preceding-sibling::node()[normalize-space()][1][self::comment()]
    

    注意:有一些重复的表达式,因为您要选择元素和注释节点。这个表达式使用了著名的数字测试习语。最后,由于不能保证只对空白文本节点的解析器设置,因此在使用normalize-space()函数之前,必须先使用位置谓词

    here中测试

    编辑:强制执行字符串长度

  2. # 2 楼答案

    您已经向需要XPath表达式的API提供了正则表达式

    可以将正则表达式与XPath结合使用,但需要支持XPath2.0或更高版本(例如Saxon)的处理器。JDK附带的XPath处理器仍然只支持古老的XPath 1.0标准,它不支持正则表达式

    不能直接向xpath.compile()提供正则表达式,但可以提供形式为//*[matches(., ' my regex ')]的XPath表达式

    如果您决定采用Saxon方法,我建议使用Saxon的内部树模型而不是DOM,因为它执行XPath的速度通常是DOM的5到10倍